#include <stdio.h>
#include <fcntl.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <unistd.h>
#include <mysql/mysql.h>
#include "./base_CGI.h"
#include "./decode.h"


int main()
{
  //获取参数
  char buf[1024 * 4] = {0};
  fprintf(stderr, "获取失败\n");
  if(Get_info(buf) < 0)
  {
    fprintf(stderr, "Get_info failed!\n");
    return 1;
  }

  fprintf(stderr, "Get_info OK\n");
  fprintf(stderr, "Get_info OK:%s\n",buf);
  urldecode(buf);
  fprintf(stderr, "Get_info OK:%s\n",buf);

  char name[1024] = {0};
  char * p = buf;
  p += strlen("name=");
  int i = 0;
  while(*p != '&' && *p != '\0')
  {
    name[i++] = *p;
    p++;
  }
  name[i++] = '\0';

  fprintf(stderr,"name :%s\n",name);


//将构造的html文件写给父进程
 int fd = open("/home/dandan/code/http/zddhttp/job_info/for_offer/table.html",O_RDONLY,666);
 if(fd < 0)
 {
   printf("\nopen failed fd %d\n",fd);
   return 0;
 }
 char c = '\0';
 int read_size = read(fd , &c, 1);
 fprintf(stderr, "read_size:%d\n",read_size);

  while(read_size)
  {
    read_size = read(fd, &c,1);
    printf("%c",c);
  }
  close(fd);

  MYSQL * connect_fd = mysql_init(NULL);
  if(mysql_real_connect(connect_fd, "127.0.0.1", "root", "1", "ForOffer", 3306, NULL, 0) == NULL)
  {
    fprintf(stderr, "mysql_real_connect failed!\n");
    return 1;
  }
  //处理字符集
  fprintf(stderr,"\n-----chow_info.c-------%d-----%s-----\n",__LINE__,__FUNCTION__);
  if ( mysql_set_character_set(connect_fd, "utf8"  )  ) 
  { 
    fprintf ( stderr , "错误, %s\n" , mysql_error( connect_fd)  ) ; 
  } 

  char sql[1024 * 5] = {0};
  sprintf(sql,"select * from info where user_name = '%s';",name);
  int ret = mysql_query(connect_fd,sql);
  if(ret < 0)
  {
    fprintf(stderr,"mysql_query failed\n");
    return 1;
  }
  
  MYSQL_RES * result = mysql_store_result(connect_fd);
  if(result == NULL)
  {
    fprintf(stderr,"mysql_store_result failed\n");
    return 1;
  }
  int rows = mysql_num_rows(result);
  fprintf(stderr,"rows :%d\n",rows);
  int fields = mysql_num_fields(result);
  fprintf(stderr,"fields :%d\n",fields);
   
  for(i = 0; i< rows; ++i)
  {
    MYSQL_ROW row = mysql_fetch_row(result);
    printf("<tr>");
    printf("<td>%d</td>",i + 1);
    printf("<td>%s</td>",row[1]);
    printf("<td>%s</td>",row[2]);
    printf("<td>%s</td>",row[3]);
    printf("<td>%s</td>",row[4]);
    printf("</tr>");
  }
  printf("</tbody><br></body><br></html>");


//            <tr>
//                <td>1</td>
//                <td>宏观经济1</td>
//                <td>经济学系1</td>
//                <td>负责人1</td>
//                <td>课程类别1</td>
//            </tr>
//            
//        </tbody>
//    </table>
//</body>
//</html>
}

